package com.dure.hotmemory.scenes;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dure.commonlib.util.FileUtils;
import com.dure.commonlib.util.PreferencesUtils;
import com.dure.commonlib.util.ToastUtils;
import com.dure.hotmemory.R;
import com.dure.hotmemory.adapters.CodeEditAdapter;
import com.dure.hotmemory.adapters.CodeGridAdapter;
import com.dure.hotmemory.bean.Code;
import com.dure.hotmemory.controllers.EditCodeController;
import com.dure.hotmemory.drawview.BaseSurfaceView;
import com.dure.hotmemory.listeners.ConfirmListener;
import com.dure.hotmemory.listeners.SelectPictureListener;
import com.dure.hotmemory.utils.DialogUtil;
import com.dure.hotmemory.utils.ShowSelectPictureDialogUtil;
import com.socks.library.KLog;

import java.io.File;
import java.util.List;

import static com.dure.hotmemory.listeners.SelectPictureListener.IMAGE_UNSPECIFIED;
import static com.dure.hotmemory.listeners.SelectPictureListener.PHOTO_GRAPH;
import static com.dure.hotmemory.listeners.SelectPictureListener.PHOTO_RESOULT;
import static com.dure.hotmemory.listeners.SelectPictureListener.PHOTO_ZOOM;

/**
 * Created by dure on 2017/5/31.
 */

public class EditCodeScene extends BaseScene {
    FrameLayout backFL, addFL;
    RecyclerView recyclerView;
    CodeEditAdapter adapter;
    EditCodeController controller;
    String codeNumber;

    public EditCodeScene(BaseSurfaceView baseSurfaceView) {
        super(baseSurfaceView);
        controller = new EditCodeController(this);
        sceneView = LayoutInflater.from(activity).inflate(R.layout.edit_code, null);
        initViews(sceneView);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            backFL.setBackgroundResource(R.drawable.white_planet_drawable);
            addFL.setBackgroundResource(R.drawable.white_planet_drawable);
        }else{
            backFL.setBackgroundResource(R.drawable.white_circle_drawable);
            addFL.setBackgroundResource(R.drawable.white_circle_drawable);
        }
    }

    private void initViews(View view) {

        backFL = (FrameLayout) view.findViewById(R.id.back_fl);
        addFL = (FrameLayout) view.findViewById(R.id.add_fl);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        recyclerView.setAdapter(adapter = new CodeEditAdapter(activity));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect,
                                       View view,
                                       RecyclerView parent,
                                       RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = 10;
                outRect.top = 10;
                outRect.right = 10;
                outRect.bottom = 60;
            }
        });

        addListener();
    }

    private void addListener() {
        backFL.setOnClickListener(activity);
        addFL.setOnClickListener(activity);
    }

    public void setCodeList(List<Code> codeList){
        if (codeList !=  null && codeList.size() > 0){
            codeNumber = codeList.get(0).number;
        }
        adapter.setCodeList(codeList);
    }

    @Override
    public void permissionGranted(int requestCode) {
        if (requestCode == 0){
            Code emptyCode = controller.getEmptyCode(codeNumber);
            emptyCode.isCreated = true;
            emptyCode.image = "";
            emptyCode.index = adapter.getCodeList().get(0).index;
            adapter.addCodeItem(emptyCode);
        }
    }

    @Override
    public void viewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_fl:
                activity.onBackPressed();
                break;
            case R.id.add_fl:

                if (PreferencesUtils.getBoolean(activity, "login_success")){
                    if (PreferencesUtils.getBoolean(activity, "paied")){
                        controller.checkPermission(Manifest.permission.CAMERA, 0, new ConfirmListener() {
                            @Override
                            public void confirmed(Bundle bundle) {
                                Code emptyCode = controller.getEmptyCode(codeNumber);
                                emptyCode.isCreated = true;
                                emptyCode.image = "";
                                emptyCode.index = adapter.getCodeList().get(0).index;
                                adapter.addCodeItem(emptyCode);
                            }
                        });

                    }else{
                        // 显示支付对话框
                        DialogUtil.showPayDialog(activity, new ConfirmListener() {
                            @Override
                            public void confirmed(Bundle bundle) {
                                String amountStr = bundle.getString("amount");
                                double amount = 0;
                                if (!TextUtils.isEmpty(amountStr)) {
                                    amount = Double.valueOf(amountStr);
                                }
                                PayScene payScene = new PayScene(baseSurfaceView);
                                payScene.setPayType("plan_pay");
                                payScene.setAmount(amount);
                                activity.moveToNewScene(payScene);
                            }
                        });
                    }
                }else{
                    ToastUtils.show(activity, "请先登录");
                }

                break;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        String fileRootDir = activity.getFilesDir().getAbsolutePath();
        String fileRootDir = Environment.getExternalStorageDirectory().getAbsolutePath();


        // 拍照
        if (requestCode == SelectPictureListener.PHOTO_GRAPH) {
            KLog.d("lesleixz", "startPhotoZoom");
            startPhotoZoom(Uri.fromFile(new File(fileRootDir, "temp.jpg")));
        }
        if (data == null)
            return;
        // 图库
        if (requestCode == SelectPictureListener.PHOTO_ZOOM) {
            startPhotoZoom(data.getData());

        }
        // 处理裁剪的图片
        if (requestCode == SelectPictureListener.PHOTO_RESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");

                Code currentEditCode = adapter.getCurrentEditCode();
                String savaFilePath = String.format(fileRootDir + "/%d.jpg", System.currentTimeMillis());
                currentEditCode.image = savaFilePath;
                KLog.d("lesleixz", "save file path = " + savaFilePath);

                // 将裁剪之后的图片保存到缓存文件中
                FileUtils.bitmapWriteToCacheDir(photo, savaFilePath);

                adapter.notifyItemChanged(adapter.getCodeList().indexOf(currentEditCode));

            }

            File tempFile = new File(fileRootDir, "temp.jpg");
            if (tempFile.exists()){
                tempFile.delete();
            }
        }

    }

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");// 调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");// 进行修剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, PHOTO_RESOULT);

    }
}
